#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023-04-17 22:06
# @Author  : wsh
# @File    : users_mapper.py
import datetime

from pymysql import IntegrityError

from model.db import reservoir_sensitivity, TbUsers
from model.db.user_model import TbProject, TbAdmin
from model.params import RoleNameEnum
from model.params.users_params import UserInfoParam, UserInfoUpdateParam, ProjectParam, RegUserParam
from util import DataNotExist, bcrypt_pwd
from util.encryption import verify_pwd
from util.exception_handlers import AllExceptionHandler, AllException, PwdNotMate


def user_login(user_name, password, role_name):
    """
    用户登录密码匹配
    """
    user = reservoir_sensitivity.query(TbUsers).filter(TbUsers.user_name == user_name,
                                                       TbUsers.role_name == role_name).first()
    if user is None:
        raise DataNotExist("用户")

    if not verify_pwd(password, user.user_pwd):
        raise PwdNotMate(user.user_name)
    return user


def userName_is_exist(user_name: str) -> bool:
    user = reservoir_sensitivity.query(TbUsers).filter(TbUsers.user_name == user_name).first()
    if user is None:
        return False
    else:
        return True


def is_activate(user_id: int) -> TbUsers:
    user = reservoir_sensitivity.query(TbUsers).filter_by(user_id=user_id, is_authorize=0).first()
    return user


def email_is_exist(email: str) -> bool:
    user = reservoir_sensitivity.query(TbUsers).filter_by(email=email).first()
    if user is None:
        return False
    else:
        return True


def get_user_by_username_null(username) -> TbUsers:
    user = reservoir_sensitivity.query(TbUsers).filter_by(user_name=username).first()
    return user


def get_user_by_username(username) -> TbUsers:
    user = reservoir_sensitivity.query(TbUsers).filter_by(user_name=username).first()
    if not user:
        raise DataNotExist("用户")
    return user


def get_user_by_email(email) -> TbUsers:
    user = reservoir_sensitivity.query(TbUsers).filter_by(email=email).first()
    if not user:
        raise DataNotExist("用户")
    return user


def get_user_by_email_null(email_msg) -> TbUsers:
    user = reservoir_sensitivity.query(TbUsers).filter_by(email=email_msg).first()
    return user


def get_user_by_id(user_id) -> TbUsers:
    """
    根据user_id获取用户信息
    :param user_id:
    :return:
    """
    user = reservoir_sensitivity.query(TbUsers).filter_by(user_id=user_id).first()
    if not user:
        raise DataNotExist("用户")
    return user


def add_user(user_info: RegUserParam) -> TbUsers:
    """
    添加用户
    :param user_info:
    :return:
    """

    try:  # 添加用户
        if user_info.role_name == RoleNameEnum.User.value:
            role_name = 'User'
        elif user_info.role_name == RoleNameEnum.Admin.value:
            role_name = 'Admin'
        else:
            role_name = 'User'
        user = TbUsers(
            user_name=user_info.user_name,
            user_pwd=bcrypt_pwd(user_info.user_pwd),
            role_name=role_name,
            company_name=user_info.company_name,
            belong_post=user_info.belong_post,
            job_name=user_info.job_name,
            true_name=user_info.true_name,
            phone=user_info.phone,
            email=user_info.email,
            group_id=user_info.group_id,
            remark=user_info.remark
        )
        reservoir_sensitivity.add(user)
        reservoir_sensitivity.commit()
        reservoir_sensitivity.flush(user)
        return user
    except Exception as e:
        reservoir_sensitivity.rollback()
        raise e


def update_user(user_id, user_info: UserInfoParam) -> TbUsers:
    """
    更新用户信息
    :param user_id:
    :param user_info:
    :return:
    """
    user = get_user_by_id(user_id)
    # if not user.is_authorize:
    #     raise UserNotActivated()
    try:
        for key, value in dict(user_info).items():
            if value:
                if key == "user_pwd":  # 若是密码，需要加密
                    setattr(user, key, bcrypt_pwd(value))
                else:
                    setattr(user, key, value)
        reservoir_sensitivity.commit()
        reservoir_sensitivity.refresh(user)
        return user
    except Exception as e:
        print("user_params.py", e, e.__traceback__.tb_lineno)
        reservoir_sensitivity.rollback()
        raise AllException("用户信息修改失败")


def activate_user(user_id, check_name) -> TbUsers:
    """
    根据user_id获取用户信息
    :param user_id:
    :return:
    """
    user = reservoir_sensitivity.query(TbUsers).filter_by(user_id=user_id).first()
    setattr(user, "is_authorize", 1)
    setattr(user, "check_date", datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    setattr(user, "check_name", check_name)
    reservoir_sensitivity.commit()
    reservoir_sensitivity.refresh(user)
    return user


def update_user_info(info: UserInfoUpdateParam) -> TbUsers:
    """
       根据user_id更新用户信息
    """
    user = reservoir_sensitivity.query(TbUsers).filter_by(user_id=info.user_id).first()
    setattr(user, "user_name", info.user_name)
    setattr(user, "job_name", info.job_name)
    setattr(user, "true_name", info.true_name)
    setattr(user, "phone", info.phone)
    setattr(user, "remark", info.remark)
    reservoir_sensitivity.commit()
    reservoir_sensitivity.refresh(user)
    return user


def update_users(id: int, users: UserInfoParam) -> TbUsers:
    # user.update(
    #     {"user_name":users.user_name,
    #     "user_pwd": users.job_name,
    #      "role_name":users.role_name,
    #      "belong_post":users.belong_post,
    #      "job_name":users.job_name,
    #      "true_name":users.true_name,
    #      "email": users.email,
    #      "group_id": users.group_id,
    #      "phone":users.phone,
    #      "remark":users.remark
    #      }
    # ))
    # reservoir_sensitivity.commit()
    user = reservoir_sensitivity.query(TbUsers).filter_by(user_id=id).first()
    setattr(user, "user_name", users.user_name)
    setattr(user, "job_name", users.job_name)
    setattr(user, "true_name", users.true_name)
    setattr(user, "phone", users.phone)
    if user.role_name == "系统管理员":
        setattr(user, "role_name", "Admin")
    if user.role_name == "普通用户":
        setattr(user, "role_name", "User")

    setattr(user, "belong_post", users.belong_post)
    setattr(user, "group_id", users.group_id)
    setattr(user, "email", users.email)
    setattr(user, "remark", users.remark)
    reservoir_sensitivity.commit()
    reservoir_sensitivity.refresh(user)
    return user


def deleteuser(user_id) -> TbUsers:
    user = reservoir_sensitivity.query(TbUsers).filter_by(user_id=user_id).first()
    reservoir_sensitivity.query(TbUsers).filter_by(user_id=user_id).delete()
    reservoir_sensitivity.commit()
    print(user)
    return user
